package com.redxiii.spike.engine.commands;

import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

import com.redxiii.spike.api.command.CommandPattern;
import com.redxiii.spike.api.communication.CommunicationService;
import com.redxiii.spike.api.message.Message;
import com.redxiii.spike.util.command.AbstractCommand;
import com.redxiii.spike.util.core.EngineSession;

/**
 * @author Daniel Filgueiras
 * @since 23/12/2011
 */
@CommandPattern(patterns = { "^//42$" })
public class ServerShutdown extends AbstractCommand {

	private final String shutdownCommand;
	private Message message;

	public ServerShutdown() {
		
		String osName = System.getProperty("os.name");
		if (osName.startsWith("Win")) {
			shutdownCommand = System.getenv("SystemRoot") + "\\System32\\shutdown.exe -s -t 42";
		} else if (osName.startsWith("Linux") || osName.startsWith("Mac")) {
			shutdownCommand = "shutdown -h now";
		} else {
			shutdownCommand = null;
		}
	}

	@Override
	public boolean proccess(Message message) {

		this.message = message;
		
		CommunicationService service = EngineSession.getCommunicationService();
		
		if (shutdownCommand == null) {
			service.reply(message, "Shutdown unsupported operating system ...");
		} else {
			service.reply(message, "Shutdown in process. 42 seconds left...");
			new Timer().schedule(new TimerTask() {
				@Override
				public void run() {
					try {
						Runtime runtime = Runtime.getRuntime();
				        Process proc = runtime.exec(shutdownCommand);
				        proc.waitFor();
					} catch (IOException e) {
						e.printStackTrace();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}

			}, 1 * 1000);
			
			new Timer().schedule(new TimerTask() {
				@Override
				public void run() {
					sendGoodBye();
				}

			}, 38 * 1000);
			
			new Timer().schedule(new TimerTask() {
				@Override
				public void run() {
					shutdownSpike();
				}

			}, 40 * 1000);
		}
		
		return true;
	}

	private void sendGoodBye() {
		EngineSession.getCommunicationService().reply(message, "Goodbye");
	}
	
	private void shutdownSpike() {
		EngineSession.sessionShutdown();
	}
}
